package com.yumi.service.Impl;

import com.yumi.common.MessageConstant;
import com.yumi.entity.Employee;
import com.yumi.mapper.EmployeeMapper;
import com.yumi.service.employeeService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class employeeServiceImpl implements employeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void inert(Employee employee) {
        employeeMapper.insert(employee);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Employee update(Long id, Employee employee) {
        // 检查员工是否存在
        Employee existEmployee = employeeMapper.selectById(id);
        if (existEmployee == null) {
            throw new RuntimeException(MessageConstant.EMPLOYEE_NOT_FOUND);
        }

        // 设置ID，防止前端传入的ID与路径ID不一致
        employee.setId(id);

        // 更新员工信息
        if (employeeMapper.updateById(employee) <= 0) {
            throw new RuntimeException(MessageConstant.UPDATE_ERROR);
        }

        // 返回更新后的员工信息
        return employeeMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        // 检查员工是否存在
        Employee employee = employeeMapper.selectById(id);
        if (employee == null) {
            throw new RuntimeException(MessageConstant.EMPLOYEE_NOT_FOUND);
        }

        // 删除员工（MyBatis-Plus已配置逻辑删除，会自动修改deleted字段）
        if (employeeMapper.deleteById(id) <= 0) {
            throw new RuntimeException(MessageConstant.DELETE_ERROR);
        }
    }

    @Override
    public Page<Employee> pageQuery(Integer pageNum, Integer pageSize) {
        Page<Employee> page = new Page<>(pageNum, pageSize);
        return employeeMapper.selectPage(page, null);
    }
}
